//var EndToEnd = function(){
function SportTrace() {
    //事件相关
    var map_mouse_move = null;
    var map_mouse_out = null;
    var map_click_handle = null;
    var wmsLayer = null; //渲染图层
    var mobile = null;
    var beginTime = null;
    var endTime = null;
    var delta_temp = null;
    var range = null;
    var trace_layer = null;
    var trace_temp = null;
    var trace_temp_1 = null;//记录偏移后的坐标信息
    var trace_same_layer = null;
    var graphic_onclick = null;
    var cur_ring_graphic = null;

    //初始化数据
    var initData = function () {
        if (trace_layer) {
            trace_layer.clear();
        }
        gis_layout.removeRightWidget('_trace_info_id');
        gis_layout.removeLeftWidget('_run_info_id');
        var start = new Date().getTime();//起始时间

        $.ajax({
            url: "/getsporttrace",
            data: {
                mobile: mobile,
                begintime: beginTime,
                endtime: endTime,
                range: range
            },
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                var end = new Date().getTime();//接受时间
                gis_common.outPut(req, function (data) {
                    createTracePoint(data, end - start);

                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };

    var createTracePoint = function (data, times) {
        trace_temp = data;
        var xmax;
        var ymax;
        var xmin;
        var ymin;
        var i = 0;
        var i_error = 0;
        var i_normal = 0;
        for (var key in data) {
            i++;
            var list = data[key];
            var traceItem = list[0];
            var point = new esri.geometry.Point(traceItem.longitude, traceItem.latitude, gis_core.map.spatialReference);
            if (traceItem.app_status == 1 || traceItem.tcp_build_chain_re_delay > 500 || traceItem.tcp_build_chain_confirm_delay > 500) {
                var symbol = new esri.symbol.PictureMarkerSymbol('/images/point.png', 26, 26);
                i_error++;
            } else {
                symbol = new esri.symbol.PictureMarkerSymbol('/images/point-green.png', 26, 26);
                i_normal++;
            }

            var graphic = new esri.Graphic(point, symbol, traceItem, null);
            trace_layer.add(graphic);
            if (!xmax || xmax < traceItem.longitude) {
                xmax = traceItem.longitude;
            }

            if (!ymax || ymax < traceItem.latitude) {
                ymax = traceItem.latitude;
            }

            if (!xmin || xmin > traceItem.longitude) {
                xmin = traceItem.longitude;
            }

            if (!ymin || ymin > traceItem.latitude) {
                ymin = traceItem.latitude;
            }

        }

        if (xmax && ymax && xmin && ymin) {
            gis_common.setExtent(xmax, ymax, xmin, ymin);
        }

        createRunTime(times, i, i_error, i_normal);

        dojo.connect(trace_layer, "onClick", capitalClick);
    };

    //----------------轨迹点点击事件开始-------------------

    var capitalClick = function (event) {
        trace_temp_1 = null;
        var lon = event.graphic.attributes.longitude;
        var lat = event.graphic.attributes.latitude;

        if (trace_same_layer) {
            trace_same_layer.clear();
        }

        if (cur_ring_graphic && cur_ring_graphic.attributes.longitude == lon && cur_ring_graphic.attributes.latitude) {
            cur_ring_graphic = null;
            return;
        }

        var key = lon + '-' + lat;
        var traceList = trace_temp[key];
        if (traceList && traceList.length > 0) {
            if (traceList.length == 1) {
                showTraceInfo(traceList[0]);
                reDrawGraphic(event.graphic);
            } else {
                addTraceRing(traceList);
                cur_ring_graphic = event.graphic;
            }
        }
    };

    var reDrawGraphic = function (graphic) {
        var old_symbol = new esri.symbol.PictureMarkerSymbol('/images/point.png', 26, 26);
        var old_symbol_green = new esri.symbol.PictureMarkerSymbol('/images/point-green.png', 26, 26);
        var new_symbol = new esri.symbol.PictureMarkerSymbol('/images/cluster.png', 26, 26);
        graphic.setSymbol(new_symbol);
        if (graphic_onclick && graphic != graphic_onclick) {
            if (graphic_onclick.attributes.app_status == 1 || graphic_onclick.attributes.tcp_build_chain_re_delay > 500 || graphic_onclick.attributes.tcp_build_chain_confirm_delay > 500) {
                graphic_onclick.setSymbol(old_symbol);
            } else {
                graphic_onclick.setSymbol(old_symbol_green);
            }
        }

        graphic_onclick = graphic;
    };

    //绘制加载时间
    var createRunTime = function (times, i, i_error, i_normal) {
        var id = '_run_info_id';
        var title = '查询时间';
        var list = [];
        list.push({id: '手机号', name: mobile});
        list.push({id: '开始时间', name: beginTime});
        list.push({id: '结束时间', name: endTime});
        list.push({id: '查询时间', name: times + "毫秒"});
        list.push({id: '轨迹点数', name: i});
        list.push({id: '正常轨迹', name: i_normal});
        list.push({id: '异常轨迹', name: i_error});
        list.push({id: '筛选规则', name: 'TCP建链响应时延（ms）>500ms 或 TCP建链确认时延（ms）>500ms 或 业务失败'});
        var divContent = gis_common.createKeyValueList(list);
        gis_layout.createLeftWidget(id, title, divContent);
    };

    var showTraceInfo = function (traceItem) {
        var id = '_trace_info_id';
        var title = '轨迹';//traceItem.name;
        var a1 = "文本";
        if (traceItem.app_content == 2) {
            a1 = '图片';
        } else if (traceItem.app_content == 3) {
            a1 = '音频';
        }
        else if (traceItem.app_content == 4) {
            a1 = '视频';
        }
        else if (traceItem.app_content == 5) {
            a1 = '其他';
        }
        var a2 = traceItem.l4_protocal == 1 ? 'TCP' : 'UDP';
        var newDate = new Date();
        newDate.setTime(traceItem.procedure_Start_Time);
        var endDate = new Date();
        endDate.setTime(traceItem.procedure_End_Time);

        //var divContent = $('<div>' + content.join('<br />') + '</div>');
        var list = [];
        list.push({id: '经度', name: traceItem.longitude});
        list.push({id: '纬度', name: traceItem.latitude});
        list.push({id: '应用内容', name: a1});
        list.push({id: 'L4协议类型', name: a2});
        list.push({id: '上行流量', name: traceItem.ul_data + '(B)'});
        list.push({id: '下行流量', name: traceItem.dl_data + '(B)'});
        list.push({id: '上行IP包数', name: traceItem.ul_ip_packet});
        list.push({id: '下行IP包数', name: traceItem.dl_ip_packet});
        list.push({id: 'TCP建链响应时延', name: traceItem.tcp_build_chain_re_delay + 'ms'});
        list.push({id: 'TCP建链确认时延', name: traceItem.tcp_build_chain_confirm_delay + 'ms'});
        list.push({id: 'TCP建链尝试次数', name: traceItem.tcp_attempts_to_build_chain});
        //list.push({id: '第一个HTTP响应包时延', name: traceItem.first_http_response_packet_delay + 'ms'});
        //list.push({id: '最后一个HTTP内容包的时延', name: traceItem.final_http_content_package_delay + 'ms'});
        //list.push({id: '最后一个ACK确认包的时延', name: traceItem.final_confirmation_packet_ack_delay + 'ms'});
        list.push({id: '访问域名', name: traceItem.host});
        //list.push({id: '访问的URI', name: traceItem.uri});
        list.push({id: 'user_agent', name: traceItem.user_agent});

        list.push({id: '经过时间', name: newDate.format('yyyy-MM-dd h:m:s') + ' - ' + endDate.format('yyyy-MM-dd h:m:s')});
        var divContent = gis_common.createKeyValueList(list);

        gis_layout.createRightWidget(id, title, divContent);
    };

    var addTraceRing = function (oriTraceList) {
        var traceList = $.extend(true, [], oriTraceList);
        var len = traceList.length;
        var angle = 360 / len;//角度
        var radius = 50;//半径
        var mercator = GPS.mercator_decrypt(radius, radius);
        var lon = mercator.lon;
        var lat = mercator.lat;
        //第一个点设置在左侧
        var list = [];
        var oriLon = traceList[0].longitude;
        var oriLat = traceList[0].latitude;
        trace_temp_1 = {};
        var dit = Math.PI * 2 / len;
        for (var i = 0; i < len; i++) {
            var newLat = oriLat + lat * Math.sin(i * dit);
            var newLon = oriLon + lon * Math.cos(i * dit);
            var item = traceList[i];
            item.longitude = newLon;
            item.latitude = newLat;
            var key = newLon + '-' + newLat;
            trace_temp_1[key] = item;
            list.push(item);

            /*------增加划线-------*/
            var line_polygon = new esri.geometry.Polygon(gis_core.map.spatialReference);
            var rings = [];
            rings.push([newLon, newLat]);
            rings.push([oriLon, oriLat]);
            line_polygon.addRing(rings);
            var line_symbol = new esri.symbol.SimpleLineSymbol().setColor(new esri.Color([255, 0, 0])).setWidth(3);
            var line_graphic = new esri.Graphic(line_polygon, line_symbol);
            trace_same_layer.add(line_graphic);
        }

        for (var j = 0, j_len = list.length; j < j_len; j++) {
            var traceItem = list[j];
            var infoTemplate = new esri.InfoTemplate();
            infoTemplate.setTitle(traceItem.name);
            var content = [];
            content.push('地名：' + traceItem.name);
            content.push('经度：' + traceItem.longitude);
            content.push('纬度：' + traceItem.latitude);
            var newDate = new Date();
            newDate.setTime(traceItem.procedure_Start_Time * 1000);
            content.push('经过时间：' + newDate.format('yyyy-MM-dd h:m:s'));
            infoTemplate.setContent('<div>' + content.join('<br />') + '</div>');
            var point = new esri.geometry.Point(traceItem.longitude, traceItem.latitude, gis_core.map.spatialReference);
            var symbol = new esri.symbol.PictureMarkerSymbol('/images/point.png', 26, 26);
            var graphic = new esri.Graphic(point, symbol, traceItem, null);
            trace_same_layer.add(graphic);
        }
        dojo.connect(trace_same_layer, "onClick", capitalClick1);

    };

    var capitalClick1 = function (event) {
        if (event.graphic.attributes) {
            var lon = event.graphic.attributes.longitude;
            var lat = event.graphic.attributes.latitude;
            var key = lon + '-' + lat;
            var traceItem = trace_temp_1[key];
            showTraceInfo(traceItem);
            reDrawGraphic(event.graphic);
        } else {

        }
    };

    //----------------轨迹点点击事件结束--------------------

    //地图改变事件
    var extentchange = function (delta) {
        delta_temp = delta;
    };

    /**
     * 渲染参数选取
     * @param callback
     */
    this.createQueryParamHtml = function (callback) {
        var content = "<div class=\"form-group\">";
        content += "	<label class='col-sm-3 control-label'>电话号码:</label>";
        content += "	<div id='res_type' class='col-sm-9'>";
        content += "			<input id='_sport_trace_mobile' type='text' class='form-control'/>";
        content += " 	</div> ";
        content += " </div > ";
        content += "<div class=\"form-group\">";
        content += "	<label class='col-sm-3 control-label'>开始时间:</label>";
        content += "	<div id='res_type' class='col-sm-9'>";
        content += "			<input id='_sport_trace_begin_time' type='text' class='form-control' onFocus=\"WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd HH'});\"/>";
        content += " 	</div> ";
        content += " </div> ";
        content += "<div class=\"form-group\">";
        content += "	<label class='col-sm-3 control-label'>结束时间:</label>";
        content += "	<div id='res_type' class='col-sm-9'>";
        content += "			<input id='_sport_trace_end_time' type='text' class='form-control' onFocus=\"WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd HH'});\"/>";
        content += " 	</div> ";
        content += " </div> ";
        content += "<div class=\"form-group\">";
        content += "	<label class='col-sm-3 control-label'>最小距离(米):</label>";
        content += "	<div id='res_type' class='col-sm-9'>";
        content += "			<input id='_sport_trace_len' type='text' value='500' class='form-control'/>";
        content += " 	</div> ";
        content += " </div> ";
        content += "<div class='form-group'>";
        content += " 	<div class='col-sm-9 col-sm-offset-3'>";
        content += "		<button id='_sport_trace_query_btn' class='btn btn-primary'>查 询</button>";
        content += "	</div>";
        content += "</div>";


        var $div = $(content);
        $div.find("#_sport_trace_query_btn").bind("click", function () {

            var $mobile = $div.find('#_sport_trace_mobile');
            mobile = $mobile.val();
            var $beginTime = $div.find("#_sport_trace_begin_time");
            beginTime = $beginTime.val();
            var $endTime = $div.find("#_sport_trace_end_time");
            endTime = $endTime.val();
            var $range = $div.find('#_sport_trace_len');
            range = $range.val();
            if (gis_common.stringIsNullOrWhiteSpace(mobile)) {
                gis_common.showMessage("请输入手机号码");
                $mobile.focus();
                return;
            }

            if (gis_common.stringIsNullOrWhiteSpace(beginTime)) {
                gis_common.showMessage("请输入查询开始时间");
                $beginTime.focus();
                return;
            }

            if (gis_common.stringIsNullOrWhiteSpace(endTime)) {
                gis_common.showMessage("请输入查询结束时间");
                $endTime.focus();
                return;
            }

            if (gis_common.stringIsNullOrWhiteSpace(range)) {
                gis_common.showMessage("请输入最小间距");
                $range.focus();
                return;
            }

            //渲染轨迹
            initData();
            $('#sportTrace_createQueryParamHtml .minus').click();
        });
        callback($div)
    };

    /**
     * 初始化
     */
    this.init = function () {
        //加载库文件
        dojo.require("esri.layers.WMSLayerInfo");
        dojo.require("esri.layers.WMSLayer");
        trace_layer = gis_core.addGraphicsLayer('sport-trace', '运动轨迹分析');
        trace_same_layer = gis_core.addGraphicsLayer('sport-trace-1', '运动轨迹分析');
        gis_core.addExtentChange("SportTrace", extentchange);
        //注册模块
        gis_core.addPlugin(this);
    };
    /**
     * 销毁
     */
    this.destroy = function () {
        gis_core.removeExtentChange("SportTrace");

        dojo.disconnect(map_mouse_move);
        dojo.disconnect(map_mouse_out);
        dojo.disconnect(map_click_handle);

        mobile = null;
        beginTime = null;
        endTime = null;
        wmsLayer = null;
        delta_temp = null;
        trace_layer = null;
        sportTrace = null;
        trace_temp = null;
        trace_temp_1 = null;
        trace_same_layer = null;
        gis_core.removeLayer('sport-trace');
        gis_core.removeLayer('sport-trace-1');
    };
    /**
     * 模块信息
     * @type {{id: string, name: string}}
     */
    this.title = {
        id: "00_01_00",
        name: "运动轨迹分析"
    };
}

//功能类 全局类
var sportTrace = null;

function initSportTrace() {
    if (sportTrace == null) {
        sportTrace = new SportTrace();
        sportTrace.init();
    }
}
//菜单 查询条件
function sportTrace_createQueryParamHtml(obj) {
    initSportTrace();
    gis_layout.createMenubarWithFun("sportTrace_createQueryParamHtml", obj, "虚拟路测", sportTrace.createQueryParamHtml)
}


Date.prototype.format = function (format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}